var liveIM = require('../../utils/live-im') ;
var TIM = require('../../miniprogram_npm/tim-wx-sdk/index');
var COS = require('../../miniprogram_npm/cos-wx-sdk-v5/index');
var WxParse = require('../../../wxParse/wxParse');

var app = getApp();
var timer=null,timer2=null;

Page({
  data: {
    liveData:{}, //直播间数据
    liveStart:false, //直播间状态
    lookCount:0, //观看量
    goodsList:[], //商品列表
    cradList:[], //卡券列表
    shareList:[], //达人帮列表
    lotteryList:[], // 抽奖列表

    showSidebar:false, //侧边栏
    showSidebarType:0, // 1 达人榜,2 弹幕设置,3 商品列表,4 卡券列表,5 图文对比
    showBarrage:false, //弹幕开关
    sliderOpacity:0, //弹幕透明度
    sliderFont:10, //字号
    sliderHight:20, //屏幕占比

    zanStart:0, //点赞动作



    showGoodsTip:false, //推送商品弹窗
    showContrastTip:false, //推送对比图弹窗
    showCradTip:false, //推送优惠券弹窗
    tipIdx:-1, //推送商品,优惠券
    contrastTip:{}, //对比图数据
    goodsMoneyTipList:[], //购买提示

    showLottery:false, //抽奖弹框
    lotteryItem:{}, // 当前抽奖
    lotteryStatus:0, // 抽奖状态
    uuidYes:'', // 当前自己中奖口令
    lotteryHistory:[], // 中奖列表
    showLotteryHistory:false, //中将列表


  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var t = this,token = wx.getStorageSync('ACCESS_TOKEN');
    t.init(t,e,token);
    wx.setKeepScreenOn({keepScreenOn: true});
  },

  init(t,e,token){
    let d=t.data,
      menuButton=wx.getMenuButtonBoundingClientRect(),
      systemInfo=wx.getSystemInfoSync();
    t.setData({
      menuButton,
      systemInfo,
      c_app:app,
      token:token,
      options:e,
      userInfo:wx.getStorageSync('USER_INFO')
    },function () {
      t.getLiveData(t,e,token);
      t.getGoodsList();
      t.getCradList();
      t.getShareList();
    })
  },

  getLiveData(t,e,token){
    app.request({
      url:getApp().api.siteinfo.apiroot+'live/getRoomInfo',
      data:{
        hosId: app.api.siteinfo.hosId2,
        userId:token,
        liveId:e.id,
        oriToken:''
      },
      success(res){
        console.log(res)
        // live_status 1:直播中，2：已结束，3：未开始
        if(res.result == 0) {
          t.setData({liveData:res, lookCount:res.look_num || 0})
          t.setLotteryList(res.lotteryData);
        }
        setTimeout(function () {
          t.setInitIM(t,token,res);
        },2000)
      }
    })
  },


  // IM
  setInitIM(t,token,roomInfo){
    const configIM = {
      options:{SDKAppID:app.api.siteinfo.SDKAppID},
      setLogLevel:1,
      user:{userID: token, userSig: roomInfo.usersig},
      //群
      group:{ groupID: roomInfo.im_group_id, type: TIM.TYPES.GRP_AVCHATROOM },
      // 接受所有群消息
      message_received:t.getImMsg,
      error(e){console.log('error-1',e)}
    }
    liveIM.init(configIM,TIM,COS,t);
  },
  getImMsg(e){
    let t = this;
    e.data.forEach(item=>{
      switch(item.type) {
        case 'TIMTextElem':
          t.getTextMsg(item,t)
          break;
        case "TIMCustomElem":
          t.getCustomMsg(item,t)
          break;
        default:
          console.log('未定义类型',item)
      }
    })
  },
  getTextMsg(e,t){
    let txt = JSON.parse(e.payload.text);
    let txtMsgList = t.data.txtMsgList;
    txtMsgList.push(txt);
    console.log('聊天',txt.txt)
    t.setData({txtMsgList})
  },
  getCustomMsg(e,t){
    switch(e.payload.data) {
      case 'pushZan':
        console.log('点赞量',e.payload.extension)
        t.setData({zanCount:t.data.zanCount+(e.payload.extension-0)})
        break;
      case "pushLook":
        console.log('观看量',e.payload.extension)
        t.setData({lookCount:t.data.lookCount+(e.payload.extension-0)})
        break;
      case "pullPlay":
        console.log('开播');
        break;
      case "pushMoney":
        console.log('购买',e.payload.extension);
        // t.setMoneyTip(e.payload.extension,t)
        break;
      case "updateGoods":
        console.log('更新商品');
        t.getGoodsList()
        break;
      case "updateCrad":
        console.log('更新卡券');
        t.getCradList()
        break;
      case "beginLottery":
        console.log('开始抽奖',e.payload.extension);
        t.startLottery(e.payload.extension)
        break;
      case "pullLottery":
        console.log('已开奖',e.payload.extension);
        t.endLotter(e.payload.extension)
        break;
      case "pullGoods":
        console.log('商品推送',e.payload.extension);
        let ex = JSON.parse(e.payload.extension);
        t.setGoodsTip(t,ex.goodsId);
        break;
      case "pullGoodsImg":
        console.log('对比图',e.payload.extension);
        t.setContrastTip(t,e.payload.extension)
        break;
      case "pullCoupon":
        console.log('优惠券',e.payload.extension);
        var data = JSON.parse(e.payload.extension)
        t.setCradTip(t,data.couponId)
        break;
      case "pullUrl":
        console.log('切换镜头',e.payload.extension);
        let ext = JSON.parse(e.payload.extension)
        t.setData({'liveData.pull_url':ext.url})
        break;
      case "pushChatMsg":
        console.log('聊天推送',e.payload.extension);
        break;
      default:
        console.log('未定义类型2',e)
    }
  },


  //商品列表
  getGoodsList(){
    let t = this,d=t.data;
    app.request({
      url:getApp().api.siteinfo.apiroot+'live/getGoodsList',
      data:{
        hosId:app.api.siteinfo.hosId2,
        liveId:d.options.id
      },
      success(e){
        e.data.length && t.setData({goodsList:e.data})
      }
    })
  },
  //卡券列表
  getCradList(){
    let t = this,d=t.data;
    app.request({
      url:getApp().api.siteinfo.apiroot+'live/couponBatchList',
      data:{
        storeId:app.api.siteinfo.acid,
        liveId:d.options.id
      },
      success(e){
        e.data.length && t.setData({cradList:e.data})
      }
    })
  },
  //达人帮列表
  getShareList(){
    let t = this,d=t.data;
    app.request({
      url:getApp().api.siteinfo.apiroot+'live/shareInfoList',
      data:{
        hosId:app.api.siteinfo.hosId2,
        liveId:d.options.id,
        page:1,
        items:20,
      },
      success(e){
        e.shareList.length && t.setData({shareList:e.shareList})
      }
    })
  },



  //侧边栏
  setShowSidebar(e){
    // 1 达人榜,2 弹幕设置,3 商品列表,4 卡券列表,5 图文对比
    var type = e.currentTarget.dataset.type;
    this.setData({
      showSidebar:true,
      showSidebarType:type, // 达人榜
    })
  },
  delShowSidebar(){
    this.setData({
      showSidebar:false
    })
  },

  // 点赞
  setZanCount(){
    let t = this;
    t.setData({
      zanStart: t.data.zanStart++,
      zanCount: t.data.zanCount++,
    });

    let message = liveIM.tim.createCustomMessage({
      to: liveIM.config.group.groupID,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {
        data: 'pushZan',
        description: '点赞+1',
        extension: '1'
      }
    });
    liveIM.tim.sendMessage(message);
  },
  //发送购买提示
  goGoods(ele){
    let d = this.data;
    let user = {
      name:d.userInfo.nickname.substring(0,2)+'**',
      img:d.userInfo.avatar_url,
    }
    let message = liveIM.tim.createCustomMessage({
      to: liveIM.config.group.groupID,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {
        data: 'pushMoney',
        description: '正在购买',
        extension: JSON.stringify(user)
      }
    });
    liveIM.tim.sendMessage(message);
    wx.navigateTo({url:ele.currentTarget.dataset.url})
  },


  //弹幕开关
  setShowBarrage(){
    this.setData({
      showBarrage:!this.data.showBarrage
    })
  },

  // 商品推送
  setGoodsTip(t,id){
    if(timer) clearTimeout(timer);
    t.data.goodsList.forEach((item,idx)=>{
      item.id == id && this.setData({
        showGoodsTip:true,
        tipIdx:idx,
        showContrastTip:false,
        showCradTip:false,
      },function () {
        timer = setTimeout(function () {
          t.setData({showGoodsTip:false})
        },60*1000)
      })
    })

  },
  //优惠券推送
  setCradTip(t,id){
    if(timer) clearTimeout(timer);
    t.data.cradList.forEach((item,idx)=>{
      item.coupon_batch_id == id && t.setData({
        showCradTip:true,
        tipIdx:idx,
        showGoodsTip:false,
        showContrastTip:false,
      },function () {
        timer = setTimeout(function () {
          t.setData({showCradTip:false})
        },60*1000)
      })
    })
  },
  // 对比图推送
  setContrastTip(t,d){
    var data = JSON.parse(d)
    if(timer) clearTimeout(timer);
    t.data.goodsList.forEach((item,idx)=>{
      item.id == data.goodsId && t.setData({
        showContrastTip:true,
        showSidebar:true,
        contrastTip:data,
        tipIdx:idx,
        showSidebarType:5,
        showGoodsTip:false,
        showCradTip:false,
      },function () {
        timer = setTimeout(function () {
          t.setData({showContrastTip:false})
        },60*1000)
      })
    })
  },
  //购买提示
  setMoneyTip(obj,t){
    let o = JSON.parse(obj);
    let l = this.data.goodsMoneyTipList;
    l.push(o)
    this.setData({goodsMoneyTipList:l})
  },
  //领取卡券
  getCard(e){
    var idx = e.currentTarget.dataset.idx,
      toast = e.currentTarget.dataset.toast,
      t = this,
      d = t.data,
      card = d.cradList[idx];
    if(card.is_over || card.status) return;
    var appUserInfo = wx.getStorageSync('appUserInfo');
    console.log(1,appUserInfo)
    wx.request({
      url:getApp().api.siteinfo.apiroot+'live/grantCouponId',
      data:{
        storeId:app.api.siteinfo.acid,
        liveId:d.options.id,
        couponBatchId:card.coupon_batch_id,
        mobile:appUserInfo.mobile,
        customerId:appUserInfo.customerId,
        access_token:d.token
      },
      success(e){
        console.log(e.data)
        var tip = e.data.is_over?'已领完':(e.data.status?'领取成功':'领取失败')
        wx.showToast({title:tip,icon:'none'})
        e.data.coupon_name = e.data.couponBatchName;
        e.data.coupon_batch_id = e.data.couponBatchId;
        d.cradList[idx] = e.data
        t.setData({cradList:d.cradList})
      }
    })

  },

  // 所有抽奖信息
  setLotteryList(lotteryData){
    let t = this,d=t.data,item=null,list=null;
    list = lotteryData.filter((m,i)=>{
      if(m.lotteryStatus==1) item=m;
      return m.lotteryStatus>0;
    });
    if(list.length<1) return;
    item || (item = list[list.length-1])
    item.recordList.forEach(i=>{i.nickname = i.nickname.substring(0,2)+'**'})
    this.setData({
      lotteryItem:item,
      lotteryStatus:item.lotteryStatus,
      lotteryList:list
    })
  },
  startLottery(ext){
    let t = this,d = t.data;
    let ex = JSON.parse(ext),idx = -1;

    d.lotteryList.forEach((item,idx)=>{
      if(item.lotteryId == ex.lotteryId) idx = idx;
    })

    if(idx >= 0) d.lotteryList[idx] = ex;
    else d.lotteryList.push(ex);

    console.log(5555)
    // 开始抽奖
    t.setData({
      lotteryStatus:1,
      lotteryItem:ex,
      lotteryList:d.lotteryList
    })
  },
  endLotter(ext){
    console.log(666)
    let t = this,d = t.data;
    // 中奖
    let ex = JSON.parse(ext),idx = -1;
    let lotteryItem,uuidYes='';

    d.lotteryList.forEach((item,idx)=>{
      if(item.lotteryId == ex.lotteryId) idx = idx;
    })
    if(idx >= 0) d.lotteryList[idx] = ex;
    else d.lotteryList.push(ex);


    ex.recordList.forEach(item=>{
      item.nickname = item.nickname.substring(0,2)+'**'
      if(item.token == d.token) uuidYes = item.uuId;
    })
    t.setData({
      lotteryList:d.lotteryList,
      lotteryItem:ex,
      uuidYes,
      lotteryStatus:2,
      showLotteryHistory:false,
      showLottery:true,
      showSidebar:false
    })
  },
  // 中奖记录
  setLotteryHistory(){
    let t = this,d = t.data;
    let lotteryHistory = [];
    d.lotteryList.forEach(item=>{
      item.recordList.forEach(l=>{
        l.lotteryName = item.lotteryName
        lotteryHistory.push(l)
      })
    })
    t.setData({
      lotteryHistory,
      showLotteryHistory:true
    })
  },
  setShowLottery(){
    this.setData({
      showLottery:true
    })
  },
  delLottery(){
    this.setData({
      showLottery:false,
      showLotteryHistory:false
    })
  },
  setCopy(e){
    console.log(e)
    wx.setClipboardData({
      data:e.currentTarget.dataset.uuid
    })
  },

  // 退出全屏
  setFullScreen(){
    wx.redirectTo({
      url:'/cheng/pages/live2/live2?id='+d.options.id
    })
  },
  catchtap(){},


  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    liveIM.tim && liveIM.kill();
  },

})
